<template>
  <div class="search-contain">
    <van-search
      v-model="value"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @cancel="$router.back()"
    />

    <div class="box">
      <div class="history" v-if="historyData.length">
        <div class="content">
          <span class="title">搜索历史</span
          ><van-icon name="delete-o" @click="clear" />
        </div>
        <div class="label">
          <span
            @click="labelSeach($event)"
            v-for="(item, index) in historyData"
            :key="index"
            >{{ item }}</span
          >
        </div>
        <van-divider />
      </div>
      <div class="hot">
        <div class="content">
          <span class="title">热门搜索</span
          ><van-icon
            :name="isEyeOpen ? 'eye-o' : 'closed-eye'"
            @click="showorhidden"
          />
        </div>
        <div class="label" v-if="isEyeOpen">
          <span
            @click="labelSeach($event)"
            v-for="(item, index) in hots"
            :key="index"
            >{{ item }}</span
          >
        </div>
        <div class="hidden" v-else>已隐藏热门搜索</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from "vue";
import { useRouter } from "vue-router";
const $router = useRouter();
const value = ref("");
const isEyeOpen = ref(true);
const historyData = ref(
  JSON.parse(localStorage.getItem("historyData") || "[]")
);
const hots = ref(["iPhone", "华为", "笔记本电脑", "游戏本", "手机"]);

// 标签搜索
const labelSeach = (event) => {
  $router.push(`/searchresult/${event.target.innerText}`);
};

const onSearch = async () => {
  if (historyData.value.includes(value.value)) {
    historyData.value = historyData.value.filter(
      (item) => item !== value.value
    );
  }
  if (historyData.value.length === 7) {
    historyData.value.pop();
  }
  await historyData.value.unshift(value.value);

  $router.push(`/searchresult/${value.value}`);
  value.value = "";
};

const clear = () => {
  historyData.value = [];
};

const showorhidden = () => {
  isEyeOpen.value = !isEyeOpen.value;
};

watch(
  historyData,
  (newV) => {
    localStorage.setItem("historyData", JSON.stringify(newV));
  },
  { deep: true }
);
</script>

<style lang="scss" scoped>
.search-contain {
  background: #fff;
  border-radius: 6px;

  .box {
    padding-bottom: 20px;

    .content {
      display: flex;
      justify-content: space-between;
      padding: 10px;

      .title {
        font-size: 16px;
        font-weight: 700;
      }

      .van-icon {
        font-size: 16px;
      }
    }

    .label {
      display: flex;
      flex-wrap: wrap;

      span {
        padding: 5px 10px;
        margin: 5px;
        font-size: 14px;
        background: #f3f5f6;
        border-radius: 6px;
      }
    }

    .hidden {
      margin-top: 15px;
      font-size: 16px;
      text-align: center;
    }
  }
}
</style>
